package com.volunteer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.volunteer.dto.LoginRequest;
import com.volunteer.dto.LoginResponse;
import com.volunteer.dto.RegisterRequest;
import com.volunteer.entity.User;
import com.volunteer.entity.VolunteerProfile;
import com.volunteer.mapper.UserMapper;
import com.volunteer.mapper.VolunteerProfileMapper;
import com.volunteer.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 认证服务
 */
@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserMapper userMapper;
    private final VolunteerProfileMapper volunteerProfileMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    private final AuthenticationManager authenticationManager;

    /**
     * 用户注册
     */
    @Transactional
    public void register(RegisterRequest request) {
        // 检查用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, request.getUsername());
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setNickname(request.getNickname() != null ? request.getNickname() : request.getUsername());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setRole("VOLUNTEER");
        user.setStatus(1);
        userMapper.insert(user);

        // 创建志愿者信息
        VolunteerProfile profile = new VolunteerProfile();
        profile.setUserId(user.getId());
        profile.setTotalHours(java.math.BigDecimal.ZERO);
        profile.setTotalPoints(0);
        volunteerProfileMapper.insert(profile);
    }

    /**
     * 用户登录
     */
    public LoginResponse login(LoginRequest request) {
        try {
            // 先查询用户是否存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, request.getUsername());
            User user = userMapper.selectOne(queryWrapper);
            
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            
            // 打印日志用于调试
            System.out.println("=== 登录调试信息 ===");
            System.out.println("用户名: " + request.getUsername());
            System.out.println("明文密码: " + request.getPassword());
            System.out.println("数据库密码: " + user.getPassword());
            System.out.println("密码匹配: " + passwordEncoder.matches(request.getPassword(), user.getPassword()));
            System.out.println("用户状态: " + user.getStatus());
            
            // 认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );

            // 生成Token
            String token = jwtUtil.generateToken(request.getUsername());

            return new LoginResponse(token, user.getUsername(), user.getNickname(), user.getRole(), user.getId());
        } catch (Exception e) {
            System.out.println("登录异常: " + e.getClass().getName() + " - " + e.getMessage());
            throw e;
        }
    }
}

